/*
Package auth
@Author   : Uyynot
@Email    : uyynot@qq.com
@Time     : 2024/2/21 14:38
@File     : verify_code_controller.go
@Project  : gohub
@Desc     :
*/
package auth

import (
	"fmt"
	"github.com/gin-gonic/gin"
	v1 "gohub/app/http/controllers/api/v1"
	"gohub/app/requests"
	"gohub/pkg/captcha"
	"gohub/pkg/logger"
	"gohub/pkg/response"
	"gohub/pkg/verifycode"
)

type VerifyCodeController struct {
	v1.BaseAPIController
}

// ShowCaptcha 显示图片验证码接口
func (vc *VerifyCodeController) ShowCaptcha(c *gin.Context) {
	//生成验证码
	id, b64s, answer, err := captcha.NewCaptcha().GenerateCaptcha()
	logger.LogIf(err)
	response.JSON(c, gin.H{
		"captcha_id":  id,
		"captcha_img": b64s,
	})
	fmt.Println(id, b64s, answer, err)
}

// SendUsingPhone 发送手机验证码
func (vc *VerifyCodeController) SendUsingPhone(c *gin.Context) {
	//验证表单
	request := requests.VerifyCodePhoneRequest{}
	if ok := requests.Validate(c, &request, requests.VerifyCodePhone); !ok {
		return
	}

	//发送sms
	if ok := verifycode.NewVerifyCode().SendSMS(request.Phone); !ok {
		response.Abort500(c, "发送短信失败")
	} else {
		response.Success(c)
	}
}

// SendUsingEmail 发送邮箱验证码
func (vc *VerifyCodeController) SendUsingEmail(c *gin.Context) {
	//验证表单
	request := requests.VerifyCodeEmailRequest{}
	if ok := requests.Validate(c, &request, requests.VerifyCodeEmail); !ok {
		return
	}

	//发送邮件
	if err := verifycode.NewVerifyCode().SendEmail(request.Email); err != nil {
		response.Abort500(c, "发送Email验证码失败")
	} else {
		response.Success(c)
	}
}
